<template>
  <div>
    <h2>所有用户信息</h2>
    <el-table :data="users.records" style="width: 100%" border>
      <el-table-column prop="id" label="ID" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="username" label="用户名" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="nickname" label="昵称" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="password" label="密码" align="center" show-overflow-tooltip></el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container" style="margin-top: 20px; text-align: center">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="users.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="users.rows"
          layout="total, sizes, prev, pager, next, jumper"
          :total="users.total"
      ></el-pagination>
    </div>

    <el-row type="flex" justify="center" style="margin-top: 20px;">
      <el-button type="danger" @click="logout">登出</el-button>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import request from "@/utils/request";
import { ElMessage } from "element-plus";

// 修改数据结构，适配后端分页响应
const users = ref({
  page: 1,      // 当前页码
  rows: 10,     // 每页条数
  total: 0,     // 总记录数
  records: []   // 用户数据列表
});

const router = useRouter();

const logout = () => {
  request.get('/logout').then(() => {
    localStorage.removeItem("token");
    router.push('/');
    ElMessage.success("登出成功");
  });
};

// 修改获取用户信息方法，添加分页参数
const getUserInfo = (page = 1, pageSize = 10) => {
  request.get('/users', {
    params: {
      page,
      pageSize
    }
  }).then(res => {
    if (res.code === 200) {
      users.value = res.data;
    } else {
      ElMessage.error(res.message);
    }
  }).catch(error => {
    ElMessage.error('获取用户列表失败，请重试');
    console.error('获取用户列表出错:', error);
  });
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  getUserInfo(1, newSize); // 切换每页数量时，重置到第一页
};

// 处理页码变化
const handleCurrentChange = (newPage) => {
  getUserInfo(newPage, users.value.rows);
};

onMounted(() => {
  getUserInfo(); // 初始化加载第一页数据
});
</script>

<style scoped>
.el-table .cell {
  font-size: 14px;
  color: #333;
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: center;
}
</style>